package com.pignest.hotel.ui.reception;

import java.util.Date;
import java.util.List;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.Button;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Label;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;

import org.zkoss.zul.Tab;
import org.zkoss.zul.Textbox;

import com.pignest.framework.util.Utils;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.Living;
import com.pignest.hotel.beans.LivingCustom;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.Memberchargehistrory;
import com.pignest.hotel.beans.TbCloseAccounts;

import com.pignest.hotel.beans.Room;
import com.pignest.hotel.beans.TbAccounts;

import com.pignest.hotel.beans.TbLiveGoodsBorrow;
import com.pignest.hotel.beans.User;

import com.pignest.hotel.definition.InComeItemType;

import com.pignest.hotel.definition.ChargeOpType;
import com.pignest.hotel.definition.PayMethod;
import com.pignest.hotel.definition.RoomLiveStatus;
import com.pignest.hotel.definition.RoomUseStatus;
import com.pignest.hotel.service.CardService;
import com.pignest.hotel.service.IncomeService;
import com.pignest.hotel.service.MemberService;
import com.pignest.hotel.service.ReceptionService;
import com.pignest.hotel.service.RoomService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.Hotel;
import com.pignest.hotel.system.InComeUtil;
import com.pignest.hotel.system.Logic;
import com.pignest.hotel.system.PrintLODOP;
import com.pignest.hotel.util.DateUtil;
import com.pignest.hotel.util.MoneyUtil;
import com.pignest.hotel.util.UIUtils;

public class CheckOutRoomWindow extends GenericAutowireComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4556633422554298035L;
	private ReceptionService receptionService;
	private MemberService memberService;
	private RoomService roomService;
	private CardService cardService;
	private Living living;
	private Room room;
	private Button queryBtn;
	private Textbox qRoomName;
	/***入住相关信息****/
	private Label roomType;
	private Label roomName;
	private Label roomPrice;
	private Label livingTime;
	/*************************/
	private Button readCardBtn;
	private Listbox addPayList;//加收列表
	
	private Label used;//总消费
	private Label storage;//总存额
	private Label balance;//余额:
	private Textbox addPay;//加收
	private Label payed;//已经付费，针对部分结账的
	
	private Listbox LivingListbox;
	private Listbox LivingCustoms;
	private Listbox AccoutsListbox;
	private Listbox GoodsBorrowListbox;
	

	private Tab checkAccountsTab;
	private Grid memberGrid;
	

	private Label checkCustomName;
	//private Label checkMemberIntegal;
	//private Label checkMemberBalance;
	//private Label checkAddIntegal;//本次积分
	
	private Listbox paymentMethod;//支付Listbox
	private Listbox invoiceListbox;
	
	private Button checkBtn;
    private Button readMemberCardBtn;
    private Button queryMemberBtn;
    private Button invalidCard;
    private Button printAcountBtn;
    
    /**会员信息*/
    private Textbox mName;
    private Textbox mCardNumber;
    private Textbox mCredit;
    private Textbox mBalance;
    private Textbox mIntegral;
	
	public void onCreate() {
		queryBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   public void onEvent(Event event) {
				   query();
			   }
		   });
		addPayList.addEventListener(Events.ON_SELECT, new EventListener(){
			   public void onEvent(Event event) {
				   initMoney();
			   }
		   });
		paymentMethod.addEventListener(Events.ON_SELECT, new EventListener(){
			   public void onEvent(Event event) {
				   String sPayMetod =UIUtils.getSelectedValue(paymentMethod);
				   if(sPayMetod.equals(PayMethod.MEMBER_CARD.name()))
				   {
					   memberGrid.setVisible(true);
				   }else{
					   memberGrid.setVisible(false);
				   }
				   
			   }
		   });
		readMemberCardBtn.addEventListener(Events.ON_USER, new EventListener(){
			   public void onEvent(Event event) {
				   readMemberCard(event);
			   }
		   });
		queryMemberBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   public void onEvent(Event event) {
				   queryMember();
			   }
		   });
		//销卡
		invalidCard.addEventListener(Events.ON_USER, new EventListener(){
			   public void onEvent(Event event) {
				   Invalid(event);
			   }
		   });
		//结账退房
		checkBtn.addEventListener(Events.ON_CLICK,new EventListener(){
			public void onEvent(Event event){
				checkOut();
			}
		});
		//读门卡
		readCardBtn.addEventListener(Events.ON_USER, new EventListener(){
			public void onEvent(Event event){
				readRoomCard(event);
				query();
			}
		});
		//打印
		printAcountBtn.addEventListener(Events.ON_CLICK, new EventListener(){
			   public void onEvent(Event event) {
				   print(living);
			   }
		   });
	}
	public void query(){
		if(qRoomName.getValue()==null||qRoomName.getValue()==""){
			UIUtils.alert("请读取门卡或者输入房间号！");
			return ;
		}else{
			room= roomService.getRoomByName(qRoomName.getValue());
			if(room==null){
				UIUtils.alert("无效的房间号！请输入正确的房间号");
				return ;
			}
		}
		living =receptionService.getLiving(room);
		if(living==null){
			UIUtils.alert("该房间没有入住信息或者已经结账了！");
			return ;
		}
		if(living.getMember()!=null){
			UIUtils.setSelectedItem(paymentMethod, PayMethod.MEMBER_CARD.name());
			memberGrid.setVisible(true);
		}else
			memberGrid.setVisible(false);
		queryLive();
		queryCustoms();
		checkRoomInfo();
		isAddInCome(living);
		queryAccount();

		initMoney();
		queryGoods();
		
		checkAccountsTab.setSelected(true);

	}
	/**初始化入住信息*/
	public void queryLive(){
		if(living!=null){
			LivingListbox.getItems().clear();
			Listitem listitem = new Listitem();
			   listitem.setValue(living.getId());
			   listitem.setParent(LivingListbox);
			   listitem.appendChild(new Listcell(living.getRoom().getName()));
			   listitem.appendChild(new Listcell(DateUtil.toString(living.getLiveTime())));
			   listitem.appendChild(new Listcell(living.getCustormName()));
			   listitem.appendChild(new Listcell(RoomLiveStatus.valueof(room.getLiveStatus()).getName()+RoomUseStatus.valueof(room.getUseStatus()).getName()));
			   listitem.appendChild(new Listcell(living.getPhone()));
			   listitem.appendChild(new Listcell(Utils.toPrice(living.getStorage())));
			   listitem.appendChild(new Listcell(Utils.toPrice(living.getUsed())));
			   listitem.appendChild(new Listcell(Utils.toPrice(living.getStorage()-living.getUsed())));
		}
		
	}
	/**
	 * 查询客人信息
	 * **/
	public void queryCustoms(){
		if(living!=null){
			LivingCustoms.getItems().clear();
			List<LivingCustom> lcs =receptionService.queryCustoms(living);
			for(LivingCustom lc:lcs){
				Listitem listitem = new Listitem();
				   listitem.setValue(lc.getId());
				   listitem.setParent(LivingCustoms);
				   listitem.appendChild(new Listcell(lc.getName()));
				   listitem.appendChild(new Listcell(lc.getCertificateno()));
				   listitem.appendChild(new Listcell(lc.getCertificatetype()));
				   listitem.appendChild(new Listcell(lc.getIshost()));
				   listitem.appendChild(new Listcell(lc.getPhone()));
			}
		}
	}
   /**
    * 核对入住信息
    * **/
	public void checkRoomInfo(){
		if(living!=null&&room!=null){
			roomType.setValue(room.getType().getName());
			roomName.setValue(room.getName());
			roomPrice.setValue(Utils.toPrice(living.getAdjustPrice()));
			livingTime.setValue(DateUtil.toFullString(living.getLiveTime()));
			checkCustomName.setValue(living.getCustormName());
		}
	}
	/**
	 * 核对消费详细信息
	 * **/
	public void queryAccount(){
		if(living!=null){
			AccoutsListbox.getItems().clear();
			List<TbAccounts> Ass =receptionService.queryAccountsNotDeposit(living);
			if(Ass==null)
				return ;
			for(TbAccounts as:Ass){
				Listitem listitem = new Listitem();
				   listitem.setValue(as.getId());
				   listitem.setParent(AccoutsListbox);
				   listitem.appendChild(new Listcell(as.getName()));
				   listitem.appendChild(new Listcell(Utils.toPrice(as.getPrice())));
				   listitem.appendChild(new Listcell(Utils.toPrice(as.getPrice2())));
				   float i =as.getCounts();
			    /*	if(i!=null)*/
			    		listitem.appendChild(new Listcell(String.valueOf(as.getCounts())));
			    	/*else
			    		listitem.appendChild(new Listcell(""));*/
			    	
				   listitem.appendChild(new Listcell(as.getEndstate()));
				   listitem.appendChild(new Listcell(as.getRemark()));
			}
		}
	}
	/**
	 * 查询物品借用情况 
	 * **/
	public void queryGoods()
	{
		if(living!=null){
			GoodsBorrowListbox.getItems().clear();
			List <TbLiveGoodsBorrow> list =receptionService.queryGoodsBorrow(living);
			for(TbLiveGoodsBorrow gb:list)
			{
				Listitem listitem = new Listitem();
		    	listitem.setValue(gb.getId());
		    	listitem.setParent(GoodsBorrowListbox);
		    	listitem.appendChild(new Listcell(gb.getTbGoods().getName()));
		    	listitem.appendChild(new Listcell(DateUtil.toString(gb.getTime())));
		    	listitem.appendChild(new Listcell(DateUtil.toString(gb.getBacktime())));
		    	Integer i=gb.getCount();
		    	if(i!=null)
		    	   listitem.appendChild(new Listcell(String.valueOf(gb.getCount())));
		    	else
		    		listitem.appendChild(new Listcell(""));
			}
		}
	}
	/***核对消费**/
	public void initMoney(){
		if(living!=null){
			living=receptionService.updateCalculate(living);
			int iAddDays =Integer.valueOf((String)UIUtils.getSelectedValue(addPayList));
			//int ibalance =living.getAvailable();
		/*	int istorage =living.getStorage();
			int iused =living.getUsed();
			
			int roomPrice =living.getAdjustPrice();
			int iAddPay=roomPrice*iAddDays/2;
			int iPayed =Services.getIncomeService().countAllDeposit(living, false);
			iused=iused+iAddPay;
			storage.setValue(Utils.toPrice(living.getStorage()));//总存款
			payed.setValue(Utils.toPrice(iPayed));//已经结账过的
			addPay.setValue(Utils.toPrice(iAddPay));//加收的
			used.setValue(Utils.toPrice(iused));
			balance.setValue(Utils.toPrice(istorage-iused));*/
			InComeUtil.countInComeSingle(living, storage, used, payed, balance, addPay, iAddDays);
			
		}
	}
	void readMemberCard(Event event)
	{
		String snr =(String)event.getData();
		Card card =cardService.getUsableMemberCard(snr);
		if(card==null)
		{
			UIUtils.alert("无效会员卡!");
			return;
		}
		Member member =memberService.queryMemberOnCard(card.getCardNumber());
		if(member==null){
			UIUtils.alert("无效会员！请联系前台");
			return ;
		}
		setMember(member);
	}
	void setMember(Member m)
	{
		if(m==null){
			UIUtils.alert("请输入正确的会员名和卡号！");
			checkBtn.setDisabled(true);
			mCredit.setValue("0");
			mBalance.setValue("0");
			mIntegral.setValue("0");
		}else
		{
			mName.setValue(m.getName());
			mCardNumber.setValue(m.getCardNo());
			Integer cre =m.getCredit();
			if(cre!=null)
			  mCredit.setValue(String.valueOf(cre));
			Integer bal =m.getBalance();
			if(bal!=null)
				mBalance.setValue(MoneyUtil.toString(bal));
			Integer gral =m.getIntegral();
			if(gral!=null)
			   mIntegral.setValue(String.valueOf(gral));
			checkBtn.setDisabled(false);
		}	
	}
	void queryMember(){
		String name =mName.getValue();
		String cardNo=mCardNumber.getValue();
		Member m=memberService.queryMemberOnCard(name,cardNo);;
		setMember(m);
	}
	 /**
		 * 退房结账
		 * 
		 * **/
		
		public void checkOut()
		{
			
			StringBuffer msg = new StringBuffer();
			StringBuffer rMsg = new StringBuffer();
			StringBuffer finalAlert =new StringBuffer();
			   finalAlert.append("谢谢你的光临");

			   msg.append("您好:").append(living.getCustormName()).append("\n");
			String rUnion="";
			String orderNo=DateUtil.toString(living.getLiveTime(), "yyyyMMddHHmmss");
			String serialNumber="";
			String checkOutNo="";
		        msg.append("结账种类:单人").append("\n");
				msg.append("房间：").append(living.getRoom().getName()).append("\n");
			String sPayMethod=UIUtils.getSelectedValue(paymentMethod);
			   msg.append("结账方式：").append(PayMethod.valueOf(sPayMethod).getDisplayName()).append("\n");
			int storage=living.getStorage();//总存款
			int comsum =Services.getIncomeService().countAllConsumsUsed(living, true,null);//除加收外的消费
			String sAddpay =addPay.getValue();
			TbAccounts ac =null;
		   // int iAddpay =Utils.toPrice(sAddpay);
		    int centAddPay =Utils.toPrice(sAddpay);
			if(centAddPay!=0){
				String sAddPayName =(String)UIUtils.getSelectedLable(addPayList);
				int addDays =Integer.valueOf((String)UIUtils.getSelectedValue(addPayList));
				float addCount =addDays/2.0f;
				  msg.append("加收：").append(sAddPayName).append("\n");
				  msg.append("加收金额:").append(Utils.toPrice(centAddPay)).append("\n");
				  ac = new TbAccounts();
				  ac.setLiving(living);
				  ac.setType(InComeItemType.JSFF.name());
				  ac.setCounts(addCount);
				  ac.setPrice(-centAddPay);
				  ac.setPrice2(centAddPay);
				  ac.setName(sAddPayName);
				  ac.setEndstate("是");
				  ac.setEndtime(new Date());
				  ac.setOpdate(DateUtil.toString(new Date(), "yyyy-MM-dd"));
				  ac.setOptime(new Date());
				  ac.setRemark(rUnion+"加收"+sAddPayName+"共计:"+Utils.toPrice(centAddPay));
			}
			
			int allComsum =comsum+centAddPay;//总消费
			int pay=storage-allComsum;//应付
			int finalPay =0;//最终应付
			msg.append("总存额：").append(Utils.toPrice(storage)).append("\n");
			msg.append("已消费：").append(Utils.toPrice(allComsum)).append("\n");
			if(pay==0){
				msg.append("本次应付:").append("0").append("\n");
				finalPay=0;
			}else if(pay<0){
				msg.append("本次应付:").append(Utils.toPrice(-pay)).append("\n");
				finalPay=-pay;
			}else{
				msg.append("本次退返:").append(Utils.toPrice(pay)).append("\n");
				finalPay=pay;
			}
			//会员增加记录
			User user =Hotel.getCurrentUser();
			Memberchargehistrory mch =null;
			if(sPayMethod.equals(PayMethod.MEMBER_CARD.name()))
			{
				//是会员
				String sCardNumber=mCardNumber.getValue();
				Member m =memberService.queryMemberOnCard(sCardNumber);
				if(m==null){
					UIUtils.alert("请用有效的会员卡结账!");
					mCardNumber.focus();
					return ;
				}
				if(finalPay!=0){
				  int mExceed =memberService.exceedBalance(m,finalPay,false);
				  int mBalance =memberService.queryMemberBalance(m);
				  if(mExceed<0){
					  UIUtils.alert("当前会员余额不够！当前余额为："+Utils.toPrice(mBalance));
					  return ;
				  }
				}else{
					mch =new Memberchargehistrory();
					mch.setMember(m);
					mch.setChargeTime(new Date());
					mch.setPrice(-allComsum);
					mch.setChargetype("非自助");
					mch.setOptype(ChargeOpType.OnConsume.name());
					mch.setRemark(DateUtil.toString(new Date(), DateUtil.HOTEL_DEFAULT_FORMAT)+":"+rUnion+rMsg.toString());
					checkOutNo=m.getCardNo();
				}
			}else if(sPayMethod.equals(PayMethod.CASH.name())){
				checkOutNo=orderNo;
				
			}else
			{
				finalAlert.append("当前是用").append(PayMethod.valueOf(sPayMethod).getDisplayName()).append("结账").append("\n");
				finalAlert.append("请结算人员"+user.getName()+"在结账完成后完成输入银行凭证单据号");
			}
			int invoice=Integer.valueOf((String)UIUtils.getSelectedValue(invoiceListbox));
			if(invoice==0){
				msg.append("未开票").append("\n");
			}else{
				msg.append("已开票").append("\n");
				finalAlert.append("请给客人开票").append("\n");
				}
			TbCloseAccounts ca = new TbCloseAccounts();
			ca.setLiving(living);
			ca.setInvoice(invoice);
			ca.setTime(new Date());
			ca.setAccounts(allComsum);
			ca.setType(PayMethod.valueOf(sPayMethod).name());
			
			ca.setUsername(user.getName());
			ca.setUserId(user.getId());
			ca.setOrderNo(orderNo);
			ca.setSerialNumber(serialNumber);
			ca.setCheckOutNo(checkOutNo);
	        if(UIUtils.confirm(msg.toString())){
	        	receptionService.allCheck(living,ca,ac, mch,pay);
	        	UIUtils.alert(finalAlert.toString());
	        	checkBtn.setDisabled(true);
	        	invalidCard.setDisabled(false);
	        	printAcountBtn.setDisabled(false);
	        	
			}
		}
		//销卡
		public void Invalid(Event event)
		{
			String curCardSnr =(String)event.getData();
			Card card =cardService.getCardBySerialNumber(curCardSnr);
			if(card==null)
			{
				UIUtils.alert("系统无此卡！");
				return ;
			}
			card.setLockNumber(null);
			card.setExpireTime(null);
			cardService.update(card);
			//String sCardDate=DateUtil.currentDateToString("yyMMddHHmm");
			Clients.evalJavaScript("Card.writeCardMessage('"+curCardSnr+"','0','0000000000',"+null+","+null+",'"+"消卡成功"+"')");
		}
		public void readRoomCard(Event event){
			String lockNumber =(String)event.getData();
			if(lockNumber.equals("")||lockNumber==null){
				UIUtils.alert("请将门卡读卡器上！");
				return ;
			}
			Room room =roomService.getRoomByLock(lockNumber);
			if(room==null)
			{
				UIUtils.alert("无此房间,或者无设置门锁号！请手动输入房间号");
				return ;
			}
			qRoomName.setValue(room.getName());
		}
		public void isAddInCome(Living l)
	    {
	    	Date liveTime =l.getLiveTime();
	    	String sCurTime =DateUtil.currentDateToString(DateUtil.DEFAULT_DATETIME_FORMAT);
			String sLiveTime =DateUtil.toString(liveTime, DateUtil.DEFAULT_DATETIME_FORMAT);
			int add=Logic.getLivingAdditionalTime(sLiveTime,sCurTime,true);
			UIUtils.setSelectedItem(addPayList,String.valueOf(add));
			
	    }
		public void initPayMethod(Living l)
		{
		  if(l.getMember()!=null)
		  {
			  UIUtils.setSelectedItem(paymentMethod, PayMethod.MEMBER_CARD.name());
			  memberGrid.setVisible(true);
		  }
		}
		public void print(Living l)
		{
			PrintLODOP print = new PrintLODOP();
			print.print(l);
		}	
}
